<?php
/**
* 	Bushido
 *
 * @category   Bushido
 * @package    Bushido_ETL
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 * @author Nathan Keyes
 * @version    $Id: Abstract.php 7 2009-11-14 22:42:08Z nkeyes $
 */

/**
 * 
 * @category   Bushido
 * @package    Bushido_ETL
 * @copyright  Copyright (c) 2008-2009 Nathan Keyes
 */
abstract class Bushido_ETL_Abstract
{
	
	/**
	 * Object with command line options
	 * 
	 * @var Zend_Console_Getopt
	 */
	protected $obj_options = NULL;
	
	/**
	 * Object with db config options
	 * 
	 * @var Zend_Config_Xml
	 */
	protected $asc_dbConfig = NULL;
	
	/**
	 * The db handle
	 * 
	 * @var Zend_Db_Adapter_Abstract
	 */
	protected $dbh = NULL;
	
	/**
	 * Array of file names to parse
	 * 
	 * @var array
	 */
	protected $ary_fileNames = NULL;
	
	/**
	 * Constructor
	 * 
	 * @return void
	 */
	public function __construct()
	{
		 // load config		 
		 
		 //get a connection to the db
		 $this->_setDbh();

	}
	
	/**
	 * 
	 * @return void
	 */
	protected abstract function _setDbh();
	
	/**
	 * Initilizes the object
	 * 
	 * @return void
	 */
	public function init()
	{
		//get commandline options
		try
		{
			$this->obj_options = new Zend_Console_Getopt(NULL);
			$this->obj_options->parse();
		}
		catch (Zend_Console_Getopt_Exception $e)
		{
			echo $e->getUsageMessage();
			exit;
		}
		
		$this->ary_fileNames = $this->obj_options->getRemainingArgs();
		
	}
	
	/**
	 * Main function to be called statically
	 * 
	 * @return void
	 */
	protected static function _main($ETLAbstractClass)
	{
		$ETLAbstract = new $ETLAbstractClass();
		$ETLAbstract->init();
		try
		{
			foreach($ETLAbstract->getFileNames() as $str_FileName)
			{
				$ETLAbstract->insertFromFile($str_FileName);
			}
		}
		catch (Exception $e)
		{
			echo $e->getMessage();
			exit;
		}
	}
	
	
	/**
	 * 
	 * @return void
	 */
	public static abstract function main();
	
	/**
	 * Reads a file and imports the contents to the db
	 * 
	 * @param string $fileName the file to read
	 * @return void
	 */
	public abstract function insertFromFile($fileName);
	
	/**
	 * Returns the file names to be parsed
	 * 
	 * @return array
	 */
	public function getFileNames()
	{
		return $this->ary_fileNames;
	}
	
	
	/**
	 * 
	 * @param $string
	 * @return string
	 */
	protected function _stripQuotes($string)
	{
		return preg_replace('/[\'\"]/', '', $string);
	}
	
	
	/**
	 * 
	 * @param $table
	 * @param $value
	 * @param $valueColumn
	 * @return string
	 */
	protected function _getValueID($table, $value, $valueColumn = 'name')
	{
		$id = $this->dbh->fetchOne("SELECT ${table}_id from $table where $valueColumn = '$value'");
		
		if(!isset($id) || $id == '')
		{
			$this->dbh->insert($table, array($valueColumn => $value));
			$id = $this->dbh->lastInsertId();
		}
		
		return $id;
	}
}
